package com.rimi.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author jerry
 * 连接池工具类
 */
public class PoolUtil {

    private static DruidDataSource druidDataSource;

    static {
        //加载jdbc.properties
        InputStream inputStream=PoolUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //
        Properties properties=new Properties();
        //解析配置文件
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            System.out.println("加载jdbc配置文件失败");
            e.printStackTrace();
        }
        //初始化连接池对象
        druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(properties.getProperty("jdbc.username"));
        druidDataSource.setPassword(properties.getProperty("jdbc.password"));
        druidDataSource.setUrl(properties.getProperty("jdbc.url"));
        druidDataSource.setDriverClassName(properties.getProperty("jdbc.driver"));
        // 打开监控功能
        try {
            druidDataSource.setFilters("stat");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过连接池获取连接对象
     * @return
     */
    public static Connection getConnection(){
        try {
            return druidDataSource.getConnection();
        } catch (SQLException e) {
            System.out.println("连接池获取连接失败");
            e.printStackTrace();
        }
        return null;
    }

}
